﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Collections.Generic;
using Yipusoft.Common.Model;
using Yipusoft.Common.BLL;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.SoldierArchives.BLL;
using System.Drawing;
using Yipusoft.SoldierArchives.Model;


public partial class BasicBase_SoldierArchive_SearchSoldiers : System.Web.UI.Page
{
    //private string  strSql.Value;
    //private string strName.Value;
    protected void Page_Load(object sender, EventArgs e)
    {
        //BindNation();
        if (!Page.IsPostBack)
        {
            BindDuty();
            BindRank();
            BindSpeciality();
            BindProvince();
            //BindBackground();
            BindCulture();
            //BindReligion();
            BindCities(ddlProvinces.SelectedValue);
            BindSpeciality(ddlSpeciality1.SelectedValue);
            BindDepartment("203001", "203006", "203007");
            BindSection(ddlDepartment.SelectedValue);
            if (ddlDepartment.Items.Count == 0)
            {
                Response.Write("<script>alert('没有权限！');history.back(0);</script>");
                return;
            }
            BindCustom();

           // TabContainer1.ActiveTabIndex = 0;
        }
    }

    private void BindCustom()
    {
       
        dlCustom.DataSource = ConditionValue.GetConditionBySetUserID(User.Identity.Name);
        dlCustom.DataBind();
    }
    private void BindProvince()
    {
        //ddlProvinces.DataSource = CodeItem.GetList("ParentID='SS000000' ORDER BY SeqID");
        //ddlProvinces.DataTextField = "ItemName";
        //ddlProvinces.DataValueField = "ItemID";
        //ddlProvinces.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlProvinces.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SS000000' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlProvinces.Items.Add(li);
        }
    }

    

    private void BindDuty()
    {
        ListItem blankLI = new ListItem("", "");
        ddlDuty.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBZW00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlDuty.Items.Add(li);
        }
        
    }

    private void BindRank()
    {
        ListItem blankLI = new ListItem("", "");
        ddlRank.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBJX00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlRank.Items.Add(li);
        }
        //ddlRank.DataSource = CodeItem.GetList("ParentID='SBJX00' ORDER BY SeqID");
        //ddlRank.DataTextField = "ItemName";
        //ddlRank.DataValueField = "ItemID";
        //ddlRank.DataBind();
    }

    private void BindSpeciality()
    {
        //ddlSpeciality1.DataSource = CodeItem.GetList("ParentID='ZY0000' ORDER BY SeqID");
        //ddlSpeciality1.DataTextField = "ItemName";
        //ddlSpeciality1.DataValueField = "ItemID";
        //ddlSpeciality1.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlSpeciality1.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='ZY0000' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlSpeciality1.Items.Add(li);
        }
    }

    

    private void BindCulture()
    {
        //ddlCulture.DataSource = CodeItem.GetList("ParentID='WHCD00' ORDER BY SeqID");
        //ddlCulture.DataTextField = "ItemName";
        //ddlCulture.DataValueField = "ItemID";
        //ddlCulture.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlCulture.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='WHCD00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlCulture.Items.Add(li);
        }
    }

    
    protected void ddlProvinces_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCities(ddlProvinces.SelectedValue);
    }

    private void BindCities(string province)
    {
        //ddlCities.DataSource = CodeItem.GetList("ParentID='"+province+"' Order by SeqID");
        //ddlCities.DataTextField = "ItemName";
        //ddlCities.DataValueField = "ItemID";
        //ddlCities.DataBind();
        ddlCities.Items.Clear();
        if (province.Trim() == "")
        {
            ListItem blankLI = new ListItem("", "");
            ddlCities.Items.Add(blankLI);
        }
        else
        {
            foreach (CodeItemInfo item in CodeItem.GetList("ParentID='" + province + "' Order by SeqID"))
            {
                ListItem li = new ListItem(item.ItemName, item.ItemID);
                ddlCities.Items.Add(li);
            }
        }
    }
    protected void ddlSpeciality1_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSpeciality(ddlSpeciality1.SelectedValue);
    }

    private void BindSpeciality(string speciality)
    {
        ddlSpeciality2.Items.Clear();
        if (speciality.Trim() == "")
        {
            ListItem blankLI = new ListItem("", "");
            ddlSpeciality2.Items.Add(blankLI);
        }
        else
        {
            ddlSpeciality2.DataSource = CodeItem.GetList("ParentID='" + speciality + "' Order by SeqID");
            ddlSpeciality2.DataTextField = "ItemName";
            ddlSpeciality2.DataValueField = "ItemID";
            ddlSpeciality2.DataBind();
        }
    }

    private void BindDepartment(string permissionAdmin, string permissionLevel, string permissionUnit)
    {
        if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionAdmin))
        {
            ListItem blankLI = new ListItem("--单位--", "");
            ddlDepartment.Items.Add(blankLI);
            strPrmission.Value = permissionAdmin;
            foreach (DepartmentInfo department in Department.GetList("RIGHT(DepartmentID, 2) = '00'"))
            {
                ddlDepartment.Items.Add(new ListItem(department.FullName, department.DepartmentID));
            }
        }
        else
        {
            ddlDepartment.DataSource = GetDepartmentList(Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID,permissionLevel, permissionUnit);
            ddlDepartment.DataTextField = "FullName";
            ddlDepartment.DataValueField = "DepartmentID";
            ddlDepartment.DataBind();
            strPrmission.Value = permissionLevel;
        }
    }

    private List<DepartmentInfo> GetDepartmentList(string departmentID,  string permissionLevel, string permissionUnit)
    {
        List<DepartmentInfo> departmentList = new List<DepartmentInfo>();        
            if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionLevel) || Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionUnit))
                   departmentList = Department.GetList("DepartmentID='" + departmentID.Substring(0, 4) + "000'");
             return departmentList;
    }

    protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSection(ddlDepartment.SelectedValue);
    }

    private void BindSection(string departmentID)
    {
        ddlSection.Items.Clear();
        if (departmentID == "")
        {
            ListItem blankLI = new ListItem("--部门--", "");
            ddlSection.Items.Add(blankLI);
        }
        else
            if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "203008") || Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "203001"))
            {
                ListItem blankLI = new ListItem("--部门--", "");
                ddlSection.Items.Add(blankLI);
                foreach (DepartmentInfo department in Department.GetList("Left(DepartmentID,4)='" + departmentID.Substring(0, 4) + "' and DepartmentID<>'" + departmentID.Substring(0, 4) + "000'"))
                {
                    ddlSection.Items.Add(new ListItem(department.FullName, department.DepartmentID));
                }
            }
            else
            {
                if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "203009"))
                {
                    ddlSection.DataSource = Department.GetList("DepartmentID='" + departmentID+"'");
                    ddlSection.DataTextField = "FullName";
                    ddlSection.DataValueField = "DepartmentID";
                    ddlSection.DataBind();
                    strPrmission.Value = "203009";
                }
            }

    }

    private void InsertContainValue(string contains,string containsName)
    {
        if (strSql.Value != "")
        {
            if (!strSql.Value.Contains(contains))
            {
                strSql.Value += " and " + contains;
                strName.Value += containsName;
            }
        }
        else
        {
            strSql.Value = contains;
            strName.Value = containsName;
        }
    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        lblCunstom.Visible = true;
        txtWhere.Visible = true;
        btnSave.Visible = true;
        //panPage.Visible = true;
        if (!chkResult.Checked)
        {
            strName.Value = "";
            strSql.Value = "";
        }
        if (SoldierName.Text.Trim() != "")
        {

            InsertContainValue("SoldierName like '%" + SoldierName.Text + "%' ", " 姓名中包含'" + SoldierName.Text + "' ");

        }


        if (ddlSex.SelectedValue != "")
        {

            InsertContainValue("Sex='" + ddlSex.SelectedValue + "'", " 性别为" + ddlSex.SelectedValue);

        }

        if (CardID.Text.Trim() != "")
        {
            InsertContainValue("CardID='" + CardID.Text + "'"," 编号为" + CardID.Text);
        }

        if (YearCount.Text != "")
        {
            InsertContainValue("Year(GetDate())-Year(JoinTime)-1" + ddlAgeOperater.SelectedValue + Convert.ToString(Convert.ToInt32(YearCount.Text)-1)," 军（工）龄" + ddlAgeOperater.SelectedItem.Text + YearCount.Text+"年");
        }

        if (ddlCities.SelectedValue != "")
        {
            InsertContainValue("Native='" + ddlCities.SelectedValue + "'", " 籍贯为" + ddlProvinces.SelectedItem.Text + ddlCities.SelectedItem.Text);
        }

        if (ddlDuty.SelectedValue != "")
        {
            InsertContainValue("Duty='" + ddlDuty.SelectedValue + "'"," 职务为" + ddlDuty.SelectedItem.Text);
        }

        if (ddlRank.SelectedValue != "")
        {
            InsertContainValue("Rank='" + ddlRank.SelectedValue + "'"," 警衔为" + ddlRank.SelectedItem.Text);
        }

        if (ddlSpeciality1.SelectedValue != "")
        {
            InsertContainValue("Rank='" + ddlSpeciality1.SelectedValue + "'"," 专业为" + ddlSpeciality1.SelectedItem.Text);
        }

        if (ddlSpeciality2.SelectedValue != "")
        {
           InsertContainValue("Speciality1='" + ddlSpeciality2.SelectedValue,"--" + ddlSpeciality2.SelectedItem.Text);
        }

        if (Birthday.Text != "")
        {
           InsertContainValue("Birth'" + ddlAgeOperater.SelectedValue + Birthday.Text," 出生日期" + ddlAgeOperater.SelectedItem.Text + YearCount.Text);
        }

        if (ddlCulture.SelectedValue != "")
        {
            InsertContainValue("Culture='" + ddlCulture.SelectedValue + "'"," 文化程度为" + ddlCulture.SelectedItem.Text);
        }

        if (ddlType.SelectedValue != "")
        {
            if (strSql.Value != "")
            {
                InsertContainValue("IsContract=" + ddlType.SelectedValue, ddlType.SelectedValue == "0" ? "现役士兵" : "合同制队员");
            }
            else
            {
                strSql.Value = "1=1 ";
                InsertContainValue("IsContract=" + ddlType.SelectedValue, ddlType.SelectedValue == "0" ? "现役士兵" : "合同制队员");
            }
            
        }

        if (!chkStauts.Checked)
        {
            InsertContainValue("ISDelete=0"," ");
            //strName.Value += "【已删除】";
        }
        else
        {
            InsertContainValue("ISDelete=1","【已删除】");
        }
        string strSql1 = "";
        string strName1="";
        if (ddlSection.SelectedValue == "")
        {
            if (ddlDepartment.SelectedValue != "")
            {
                strSql1 = "DepartmentID like '" + ddlDepartment.SelectedValue.Substring(0, 4) + "%'";
                strName1=" 隶属于"+ddlDepartment.SelectedItem.Text;
            }
        }
        else
        {
            strSql1="DepartmentID='"+ddlSection.SelectedValue+"'";
            strName1=" 所在单位为"+ddlSection.SelectedItem.Text;
        }
        if (!strSql.Value.Contains(strSql1))
        {
            strSql.Value += strSql.Value.Trim()==""?strSql1:" and "+strSql1;
            strName.Value += strName1;
        }      

        lblDescription.Text ="描述："+ strName.Value;
        BindSoldiers(strSql.Value,20,0);

    }

    private void BindSoldiers(string sql,int pageSize,int pageIndex)
    {
        if (!panPage.Visible)
            panPage.Visible = true;
        Soldier soldier = new Soldier();
        int totalCount = soldier.GetSoldiersCountByWhere(sql);
        ViewState["PageCount"] = Convert.ToInt32(Math.Ceiling((double)totalCount/pageSize));
        if ((int)ViewState["PageCount"]<pageIndex)
            pageIndex = pageIndex-1;       
        ViewState["PageIndex"] = pageIndex;        
        gvSoldiers.DataSource = soldier.GetSoldiersByWhere(sql, "DepartmentID", "ASC", pageSize, pageIndex);
        gvSoldiers.DataBind();       
        lbGridInfo.Text = "共有<b>" + totalCount.ToString() + "</b>条记录 第<b>" + ((int)ViewState["PageIndex"]+1).ToString() + "</b>页 共<b>" + ViewState["PageCount"].ToString() + "</b>页 每页<b>" + pageSize.ToString() + "</b>条";
        this.btnFirst.Enabled = (int)ViewState["PageIndex"] > 0;
        this.btnPrev.Enabled = (int)ViewState["PageIndex"] > 0;
        this.btnNext.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"] - 1;
        this.btnLast.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"] - 1;
        BindJumpList();
    }

    protected void JumpList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSoldiers(strSql.Value,20,int.Parse(JumpList.SelectedValue));
    }
    protected void btnFirst_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = 0;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    protected void btnPrev_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] - 1;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] + 1;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    protected void btnLast_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageCount"] - 1;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    private void BindJumpList()
    {
        JumpList.Items.Clear();
        ListItem li;
        for (int i = 0; i < (int)ViewState["PageCount"]; i++)
        {
            li = new ListItem();
            li.Text = (i + 1).ToString();
            li.Value = i.ToString();
            JumpList.Items.Add(li);
        }
        JumpList.SelectedIndex = JumpList.Items.IndexOf(JumpList.Items.FindByValue(ViewState["PageIndex"].ToString()));
    }
    protected void gvSoldiers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string accountDepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;

        bool endableDelete = false;
        if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203001"))
            endableDelete = true;
        else
            if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203008") && accountDepartmentID.Substring(0, 4) == gvSoldiers.DataKeys[e.RowIndex].Values["DepartmentID"].ToString().Substring(0, 4))
                endableDelete = true;
            else
                if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203009") && accountDepartmentID == gvSoldiers.DataKeys[e.RowIndex].Values["DepartmentID"].ToString())
                    endableDelete = true;
        if (endableDelete)
        {
            Soldier soldier = new Soldier();
            if (soldier.Delete(gvSoldiers.DataKeys[e.RowIndex].Values["SoldierID"].ToString(), "人工删除", DateTime.Now, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName))
            {
                lblInfo.ForeColor = Color.Black;
                lblInfo.Text = "删除成功。";
                BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
            }

            else
            {
                lblInfo.ForeColor = Color.Red;
                lblInfo.Text = "删除失败！";
            }
        }
        else
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "您无权删除此兵员记录！";
        }
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        int maxCount=10;
        if (ConditionValue.GetConditionBySetUserID(User.Identity.Name).Count < maxCount)
        {
            string conditionName = txtWhere.Text == "" ? DateTime.Now.ToString("yy年M月d日HH：mm的查询条件") : txtWhere.Text;
            if (ConditionValue.Insert(conditionName, strSql.Value, lblDescription.Text, strPrmission.Value, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID) > 0)
            {                
                Label2.Text = "定制查询条件保存成功。";
                lblCunstom.Visible = false;
                txtWhere.Visible = false;
                btnSave.Visible = false;
                BindCustom();
            }
            else
            {
                Label2.Text = "保存失败！请确认没有同名的定制查询名称。";
            }
        }
        else
            Label2.Text = "您最多只能添加"+maxCount.ToString()+"个定制查询。";
    }

    protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
    {
        if (TabContainer1.ActiveTabIndex == 1)
            BindCustom();
    }


    protected void dlCustom_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            ConditionInfo conditionInfo = ConditionValue.GetConditionByID(Convert.ToInt32(dlCustom.DataKeys[e.Item.ItemIndex].ToString()));
            if (Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID == conditionInfo.DepartmentID)
            {
                if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, conditionInfo.Permission))
                {
                    lblStrName.Text = conditionInfo.Description;
                    //TabContainer1.ActiveTabIndex = 0;            
                    strSql.Value = conditionInfo.ConditionSql;
                    strName.Value = conditionInfo.Description;
                    Label2.Text = conditionInfo.ConditionName;
                    lblDescription.Text = conditionInfo.Description;
                    BindSoldiers(conditionInfo.ConditionSql, 20, 0);
                    TabContainer1.ActiveTabIndex = 0;
                }
                else
                    lblStrName.Text = "您的不再有搜索此条件的权限。";
            }
        }
        else
            lblStrName.Text = "由于您的工作调动，请重新制定搜索条件。";
       
    }
    protected void dlCustom_DeleteCommand(object source, DataListCommandEventArgs e)
    {
        if (ConditionValue.DeleteCondition(Convert.ToInt32(dlCustom.DataKeys[e.Item.ItemIndex].ToString())))
        {
            BindCustom();
        }
        //lblStrName.Text=dlCustom.DataKeys[e.Item.ItemIndex].ToString();
        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        TabContainer1.ActiveTabIndex = 0;
    }
    protected void gvCustom_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            TabContainer1.ActiveTabIndex = 0;
        }
    }
}
